package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ArticleHomeMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleHomeService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.article.dto.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ArticleVo;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.behavior.ApUserBehaviorDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.CommentSelectDto;
import com.heima.model.wemedia.dtos.WeMediaCommentDto;
import com.heima.model.wemedia.vo.WeMediaCommentVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class ArticleHomeServiceImpl extends ServiceImpl<ArticleHomeMapper, ApArticle> implements ArticleHomeService {

    private static final short PAGE_MAX_SIZE = 50;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private ArticleHomeMapper articleHomeMapper;

    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        //设置参数
        //1、分页size
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        dto.setSize(Math.min(dto.getSize(), PAGE_MAX_SIZE));
        //2、频道ID
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //3、类型type
        //4、时间
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());

        List<ApArticle> apArticles = articleHomeMapper.loadArticleList(dto, type);

        return ResponseResult.okResult(apArticles);
    }

    /**
     * 加载
     *
     * @param dto
     * @param type
     * @param firstPage
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, Boolean firstPage) {
        //如果是首页加载，直接取缓存数据
        if (firstPage) {
            String jsonString = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(jsonString)) {
                List<HotArticleVo> articleVos = JSON.parseArray(jsonString, HotArticleVo.class);
                return ResponseResult.okResult(articleVos);
            }
        }
        return load(dto, type);
    }

    /**
     * 保存或修改文章
     *
     * @param dto
     * @return
     */
    @Autowired
    private ApArticleContentMapper contentMapper;
    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private ArticleFreemarkerService freemarkerService;

    @Override
    public ResponseResult saveOrUpdateArticle(ArticleDto dto) {
        /*try {
            log.info("接下来开始睡眠三秒----->");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        //参数判断
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //进行属性复制
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //判断是否有id
        if (dto.getId() != null) {
            updateArticle(dto, apArticle);
        } else {
            saveArticle(dto, apArticle);
        }
        //生成静态文件上传到minIO
        freemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        //结果返回文章id
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 更新文章表阅读数量
     *
     * @param apUserBehaviorDto
     */
    @Override
    public void updateReadCount(ApUserBehaviorDto apUserBehaviorDto) {
        if (apUserBehaviorDto != null) {
            Long articleId = Long.valueOf(apUserBehaviorDto.getArticleId());
            ApArticle apArticle = getById(articleId);
            if (apArticle != null) {
                Integer views = apArticle.getViews();
                LambdaUpdateWrapper<ApArticle> wrapper = new LambdaUpdateWrapper<>();
                if (views == null) {
                    wrapper.set(ApArticle::getViews, 1)
                            .eq(ApArticle::getId, articleId);
                } else {
                    views += 1;
                    wrapper.set(ApArticle::getViews, views)
                            .eq(ApArticle::getId, articleId);
                }
                update(wrapper);
            }
        }
    }


    /**
     * 查询文章评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findComments(WeMediaCommentDto dto) {
        log.info("===========<{}", dto);
        //使用xml分页查询
        Integer page = dto.getPage();
        Integer size = dto.getSize();
        int index = (page - 1) * size;
        CommentSelectDto commentSelectDto = new CommentSelectDto();
        //进行属性复制
        BeanUtils.copyProperties(dto, commentSelectDto);
        //设置分页第一个属性
        commentSelectDto.setIndex(index);
        //分页查询数据
        List<WeMediaCommentVo> comments = articleHomeMapper.findComments(commentSelectDto);
        //查询总数
        Integer total = articleHomeMapper.findTotal(commentSelectDto);
        PageResponseResult responseResult = new PageResponseResult(page, size, total);
        responseResult.setData(comments);
        return responseResult;
    }

    /**
     * 保存文章   更新配置   更新内容表
     *
     * @param dto
     * @param apArticle
     */
    private void saveArticle(ArticleDto dto, ApArticle apArticle) {
        //无  保存文章
        save(apArticle);
        //保存文章配置
        ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
        configMapper.insert(apArticleConfig);
        //保存文章内容
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(dto.getContent());
        apArticleContent.setArticleId(apArticle.getId());
        contentMapper.insert(apArticleContent);
    }

    /**
     * 更新APP端文章表和内容表
     *
     * @param dto
     * @param apArticle
     */
    private void updateArticle(ArticleDto dto, ApArticle apArticle) {
        //有  修改文章
        updateById(apArticle);
        //修改文章内容
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, dto.getId());
        ApArticleContent apArticleContent = contentMapper.selectOne(wrapper);
        //重新设置内容
        apArticleContent.setContent(dto.getContent());
        //更新数据库
        contentMapper.updateById(apArticleContent);
    }
}
